package com.tywj.panda

import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.RadioGroup
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig
import com.mobile.auth.gatewayauth.AuthUIConfig
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper
import com.mobile.auth.gatewayauth.TokenResultListener
import com.mobile.auth.gatewayauth.model.TokenRet
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate
import com.tywj.panda.customer.common.constant.ThirdPartyAccount
import com.tywj.panda.customer.common.entity.LoginEntity
import com.tywj.panda.customer.common.entity.WxAccessTokenEntity
import com.tywj.panda.customer.common.event.UserEvent
import com.tywj.panda.customer.common.http.PDObjectCallback
import com.tywj.panda.customer.common.http.PDWXTokenObjectCallback
import com.tywj.panda.customer.common.manager.AuthorityManager
import com.tywj.panda.customer.common.provider.ILaunchService
import com.tywj.panda.customer.common.tool.AppEnvTool
import com.tywj.panda.customer.common.view.base.PDBaseWithoutAdaptActivity
import com.tywj.panda.launch.R
import com.tywj.panda.launch.api.LaunchApi
import com.tywj.panda.launch.route.LaunchRoute
import com.tywj.lib.core.common.extension.gone
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.extension.visible
import com.tywj.lib.core.common.util.BarUtil
import com.tywj.lib.core.common.util.LogUtil
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.lib.route.RouteUtil
import com.tywj.lib.social.SocialUtil
import com.tywj.lib.social.interfaces.IWeChatLoginCallBack


/**
 * @desc 一键登录界面
 * @author June Yang
 * @date 2020/5/8
 */

@Deprecated("废弃，在手机号登录界面上弹出")
@Route(path = LaunchRoute.AUTH_LOGIN)
class LoginAuthActivity : PDBaseWithoutAdaptActivity() {

    private var mTokenListener: TokenResultListener? = null

    private var mAlicomAuthHelper: PhoneNumberAuthHelper? = null

    private lateinit var weLoginCallBack: IWeChatLoginCallBack

    private var token = ""

    //登录方式，默认用户  1- 用户  2-司机
    private var userType = 1


    companion object {

        const val SERVICE_TYPE_AUTH = 1 //号码认证

        const val SERVICE_TYPE_LOGIN = 2 //一键登录

        const val AUTH_CODE = 2 //

        const val AUTH_TIME_OUT = 5000 //超时时间

        const val AUTH_TIME_DELAY = 1000L //延时时间

        const val AUTH_USER_CANCEL_LOGIN = "700000" //用户取消登录

        const val AUTH_USER_AUTH_PHONE_FAIL = "600011" //获得的手机授权码失败

        const val AUTH_USER_AUTH_SUCCESS = "600000" //获取token成功

        const val AUTH_USER_MOBILE_NET = "600008" //用户移动网络未启用
    }


    override fun getLayoutID(): Int = R.layout.launch_activity_auth_login


    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)
        init()
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        BarUtil.setStatusBarColor(this, ResourcesUtil.getColor(R.color.common_white))
        configLoginTokenPort()
    }

    override fun initListener() {
        super.initListener()
        initWeChatCallBack()

        //手机号登录成功后关闭界面
        UserEvent.closeAuthLoginUI.observe(this, Observer {

            mAlicomAuthHelper?.quitLoginPage()
            mAlicomAuthHelper?.hideLoginLoading()
            finish()
        })
    }

    private fun init() {
        /*
         *   1.init get token callback Listener
         */mTokenListener = object : TokenResultListener {
            override fun onTokenSuccess(ret: String) {

                runOnUiThread(Runnable {
                    Log.e("xxxxxx", "onTokenSuccess:$ret")
                    dismissLoadingDialog()

                    var tokenRet: TokenRet? = null
                    try {
                        tokenRet = JSON.parseObject(ret, TokenRet::class.java)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    if (tokenRet != null && "600024" == tokenRet.code) {
                        LogUtil.d("设备支持:\n$ret")
                        //第一步检查设备是否支持一键登录
                    }
                    if (tokenRet != null && "600001" == tokenRet.code) {
                        LogUtil.d("唤起授权页成功:\n$ret")
                        //不能关闭当界面界面，此后获取token成功后还需要登录到自己的服务器
                    }

                    if (tokenRet != null && AUTH_USER_AUTH_SUCCESS == tokenRet.code) {
                        token = tokenRet.token
                        toLogin(token)
                    }
                })
            }

            //流程说明：如果移动网络未开启，跳到手机号登录  ,获取登录Token时也会失败
            override fun onTokenFailed(ret: String) {
                Log.e("xxxxxx", "onTokenFailed:$ret")
                dismissLoadingDialog()
                var tokenRet: TokenRet? = null

                try {
                    tokenRet = JSON.parseObject(ret, TokenRet::class.java)
                } catch (e: Exception) {
                    e.printStackTrace()
                }

                if (tokenRet != null && tokenRet?.code == AUTH_USER_CANCEL_LOGIN) {
                    shortToast(R.string.launch_cancel_login)
                    //用户取消登录
                    mAlicomAuthHelper?.quitLoginPage()
                    mAlicomAuthHelper?.hideLoginLoading()
                    finish()
                    return
                }
                runOnUiThread {
                    /**
                     * 退出登录授权页时，授权页的loading消失由APP控制
                     * SDK 完成回调后，不会立即关闭授权页面，需要开发者主动调用离开授权页面方法去完成页面的关闭
                     * SDK回调完成后，不会立即关闭loading dialog，需要开发者主动调用loading效果方法去关闭loading dialog
                     */
                    mAlicomAuthHelper?.hideLoginLoading()
                    mAlicomAuthHelper?.quitLoginPage()

                    //跳到手机号登录
                    toLoginByPhone()

                    finish()
                }

            }
        }

        /*
        *   2.初始化SDK实例
        */

        mAlicomAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenListener)


        mAlicomAuthHelper?.setAuthListener(mTokenListener)

        /*
         *   3.set debugMode when app is in debug mode, sdk will print log in debug mode
         */
        mAlicomAuthHelper?.setLoggerEnable(AppEnvTool.isDev)

        /**
         * 4.设置sdk秘钥信息
         * @param  方案对应的秘钥，请登录阿里云控制台后，进入认证方案管理，点击秘钥后复制秘钥，建议维护在业务服务端
         */
        mAlicomAuthHelper?.setAuthSDKInfo(ThirdPartyAccount.ALI_AUTH_KEY)

        /**
         * 5.检测终端网络环境是否支持一键登录或者号码认证
         */

        val isSupport = mAlicomAuthHelper?.checkEnvAvailable()

        if (isSupport!!) {
            toAuthLogin()
        } else {
            //跳到手机号登录
            toLoginByPhone()
            finish()
        }
    }

    /**
     * 或步骤5支持，则根据业务情况，调用预取号或者一键登录接口
     */
    private fun toAuthLogin() {
        showLoadingDialog()
        mAlicomAuthHelper?.getLoginToken(this, AUTH_TIME_OUT)
    }


    private fun configLoginTokenPort() {
        mAlicomAuthHelper?.removeAuthRegisterXmlConfig()
        mAlicomAuthHelper?.removeAuthRegisterViewConfig()

        //其他登录方式
        mAlicomAuthHelper?.addAuthRegisterXmlConfig(
            AuthRegisterXmlConfig.Builder()
                .setLayout(R.layout.launch_customer_view, object : AbstractPnsViewDelegate() {
                    override fun onViewCreated(view: View) {


                        val radioGroup = view.findViewById(R.id.loginCheckLogin) as RadioGroup

                        val loginByWeChat = view.findViewById(R.id.ivWechat) as ImageView


                        radioGroup.setOnCheckedChangeListener { _, checkedId ->
                            when (checkedId) {
                                R.id.loginRbCustomer -> {
                                    shortToast("用户")
                                    userType = 1
                                    visible(loginByWeChat)
                                }
                                R.id.loginRbDriver -> {
                                    shortToast("司机")
                                    userType = 2
                                    gone(loginByWeChat)
                                }
                            }
                        }

                        findViewById(R.id.tvChangeOtherPhone).onClick {
                            toLoginByPhone()
                        }

                        loginByWeChat.onClick {
                            SocialUtil.login.weChatLogin.weChatLogin(weLoginCallBack)
                        }

                        findViewById(R.id.ivQQ).onClick {
                            shortToast("QQ")
                        }

                        findViewById(R.id.ivAli).onClick {
                            shortToast("ali")
                        }
                    }
                })
                .build()
        )

        var authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {
            authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_BEHIND
        }

        mAlicomAuthHelper?.setAuthUIConfig(
            AuthUIConfig.Builder()
                //TODO:换成公司的链接
                .setAppPrivacyOne("《胖哒用户协议》", "http://www.cd917.com")
                .setAppPrivacyColor(
                    ResourcesUtil.getColor(R.color.common_gray_B2),
                    ResourcesUtil.getColor(R.color.common_yellow_FE)
                )
                .setNavReturnImgPath("common_back_black")
                .setNavReturnHidden(false)
                .setPrivacyState(true)
                .setSloganText(ResourcesUtil.getString(R.string.launch_slogan_text))
                .setCheckboxHidden(false)
                //状态栏颜色
                .setStatusBarColor(ResourcesUtil.getColor(R.color.common_transparent))
                //设置标题栏内容
                .setNavText("")
                //导航栏主题色
                .setNavColor(ResourcesUtil.getColor(R.color.common_transparent))
                //设置logo图片
                .setLogoImgPath("common_login_logo")
                .setLogoHeight(88)
                .setLogoWidth(88)
                //设置按钮文字
                .setLogBtnText(ResourcesUtil.getString(R.string.launch_auth_login))
                .setLogBtnTextSize(18)
                //设置登录按钮背景图片路径  图片在drawable-xxhdpi/launch_login_bg.png则传入参数"launch_login_bg"不加后缀
                .setLogBtnBackgroundPath("launch_login_bg")
                .setLogBtnTextColor(ResourcesUtil.getColor(R.color.common_black_33))
                .setLightColor(true)
                .setSwitchAccText("")
                .setSwitchAccTextColor(ResourcesUtil.getColor(R.color.common_black_33))
                .setSwitchAccTextSize(14)
                //设置全屏幕页面的属性 进场动画
//                .setAuthPageActIn("in_activity", "out_activity")
                // //退场动画
                .setAuthPageActOut("in_activity", "out_activity")
                .setVendorPrivacyPrefix("《")
                .setVendorPrivacySuffix("》")
                .setCheckedImgPath("common_rb_oval_checked")
                .setPrivacyBefore(ResourcesUtil.getString(R.string.launch_login_is_agree))
                //设置协议页顶部导航栏背景色不设置则与授权页设置一致
                .setWebNavColor(ResourcesUtil.getColor(R.color.common_yellow_FE))
                .setScreenOrientation(authPageOrientation)
                .create()
        )
    }

    private fun toLogin(token: String) {
        showLoadingDialog()
        LaunchApi.login(aliAccessToken = token, userType = userType, loginType = 1).attachToLifecycle(this)
            .execute(object : PDObjectCallback<LoginEntity>(LoginEntity::class.java) {
                override fun success(data: LoginEntity) {
                    //登录成功状态处理
                    UserEvent.loadUserDataSuccessEvent.post(data.uid)

                    AuthorityManager.updateToken(data.token)

                    AuthorityManager.saveUid(data.uid)
                    AuthorityManager.saveLoginType(userType)

                    if (userType == 1) {
                        AuthorityManager.updateRongYunToken(data.rongyunToken)
                        shortToast("用户登录成功")
                    } else {
                        shortToast("司机登录成功")
                    }

                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    shortToast(code.toString())
                    //登录失败状态处理
                }

                override fun onComplete() {
                    super.onComplete()
                    dismissLoadingDialog()

                    /**
                     * 退出登录授权页,授权页的退出完全由APP 控制，注意需要在主线程调用此函数  ！！！！
                     * SDK 完成回调后，不会立即关闭授权页面，需要开发者主动调用离开授权页面方法去完成页面的关闭
                     */
                    mAlicomAuthHelper?.quitLoginPage()
                    finish()
                }
            })
    }

    private fun toLoginByPhone() {
        RouteUtil.getServiceProvider(ILaunchService::class.java)
            ?.toLoginByPhone()
            ?.navigation(this@LoginAuthActivity)
    }

    private fun initWeChatCallBack() {
        //微信回调
        weLoginCallBack = object : IWeChatLoginCallBack {
            override fun onSuccess(code: String) {
                getAccessToken(code)
                LogUtil.d("weChat---getAccessToken:$code")
            }

            override fun onError(errorId: Int, msg: String) {
                shortToast(msg)
            }
        }
    }

    private fun getAccessToken(code: String) {
        if (code.isEmpty()) return
        LaunchApi.getAccessToken(code).attachToLifecycle(this)
            .execute(object : PDWXTokenObjectCallback<WxAccessTokenEntity>(WxAccessTokenEntity::class.java) {
                override fun success(data: WxAccessTokenEntity) {
                    LogUtil.d("weChat--accessToken" + data.accessToken + ",openID=" + data.openid, true)
                    loginByWeChat(data.openid, data.accessToken)

                }

                override fun onError(code: Int, message: String) {
                    super.onError(code, message)
                    shortToast(message)
                }
            })
    }

    /**
     * 微信登录向平台检查用户状态
     *
     */
    private fun loginByWeChat(openId: String, accessToken: String) {
        if (openId.isEmpty() || accessToken.isEmpty()) return
        showLoadingDialog()

        LaunchApi.login(openId = openId, wxAccessToken = accessToken, loginType = 2).attachToLifecycle(this)
            .execute(object : PDObjectCallback<LoginEntity>(LoginEntity::class.java) {
                override fun success(data: LoginEntity) {
                    LogUtil.d("weChat--data:$data")
                    shortToast("微信登录成功:token==" + data.token)
                    //登录成功状态处理
                    UserEvent.loadUserDataSuccessEvent.post(data.uid)

                    AuthorityManager.updateToken(data.token)
                    AuthorityManager.updateRongYunToken(data.rongyunToken)

                    AuthorityManager.saveUid(data.uid)
                    AuthorityManager.saveLoginType(userType)
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    shortToast(message)
                    //登录失败状态处理
                }

                override fun onComplete() {
                    super.onComplete()
                    dismissLoadingDialog()

                    /**
                     * 退出登录授权页,授权页的退出完全由APP 控制，注意需要在主线程调用此函数  ！！！！
                     * SDK 完成回调后，不会立即关闭授权页面，需要开发者主动调用离开授权页面方法去完成页面的关闭
                     */
                    mAlicomAuthHelper?.quitLoginPage()
                    finish()
                }
            })
    }
}